<?php


namespace app\api\controller\v1;


use app\common\controller\Api;
use app\extra\wx\WxSdk;
use think\Db;

/**
 * 内容接口，口均不需登入
 */
class Content extends Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 首页Banner
     * @ApiMethod (GET)
     */
    public function indexBanner()
    {
        if ($this->request->isGet()) {

            $type = [
                1 => '场馆',
                2 => '教练',
                3 => '单页'
            ];
            $result = Db::name('content_banner')
                ->order('weigh', 'desc')
                ->select();

            if ($result) {
                foreach ($result as &$item) {
                    $item['image'] = self::patch_cdn($item['image']);
                    $item['type_text'] = $type[$item['type']];
                }

                $this->success('获取成功', $result);
            } else {
                $this->error('获取失败');
            }
        } else {
            $this->error(ErrorCode::$ERROR['ERROR_METHOD']);
        }
    }

    /**
     * 热门教练
     * @ApiMethod (GET)
     * @param float $longitude 经度
     * @param float $latitude 纬度
     */
    public function indexCoach()
    {
        if ($this->request->isGet()) {

            $longitude = input('longitude');
            $latitude = input('latitude');

            if (!$longitude || !$latitude) $this->error('请传入经纬度');

            $where = ['status' => 1];
            $distance = "(6378.138 * 2 * asin(sqrt(pow(sin((latitude * pi() / 180 - " . $latitude . " * pi() / 180) / 2),2) + cos(latitude * pi() / 180) * cos(" . $latitude . " * pi() / 180) * pow(sin((longitude * pi() / 180 - " . $longitude . " * pi() / 180) / 2),2))) * 1000)";

            $result = Db::name('coach')
                ->where($where)
                ->where($distance . '< ' . 1000000000)
                ->field("$distance as distance,name,portrait_image,speciality,id,speciality_ids")
                ->order('likes', 'desc')
                ->paginate(null, false, $this->paginate)
                ->each(function ($item) {
                    $speciality_ids = Db::name('category')->whereIn('id', $item['speciality_ids'])->field('name')->select();
                    if (count($speciality_ids) > 0) {
                        $speciality = [];
                        foreach ($speciality_ids as $i => $v) {
                            $speciality[$i] = $v['name'];
                        }
                        $item['speciality'] = implode(',', $speciality);
                    }
                    $item['portrait_image'] = self::patch_cdn($item['portrait_image']);
                    $item['distance'] = round(($item['distance'] / 1000), 2);
                    return $item;
                });

            $this->success('获取成功', $result);
        } else {
            $this->error(ErrorCode::$ERROR['ERROR_METHOD']);
        }
    }

    /**
     * 热门场馆
     * @ApiMethod (GET)
     * @param float $longitude 经度
     * @param float $latitude 纬度
     */
    public function indexGymnasium()
    {
        if ($this->request->isGet()) {

            $longitude = input('longitude');
            $latitude = input('latitude');

            if (!$longitude || !$latitude) $this->error('请传入经纬度');

            $join = [
                0 => '未选择',
                1 => '参与',
                2 => '不参与',
            ];

            $where = ['status' => 1];
            $distance = "(6378.138 * 2 * asin(sqrt(pow(sin((latitude * pi() / 180 - " . $latitude . " * pi() / 180) / 2),2) + cos(latitude * pi() / 180) * cos(" . $latitude . " * pi() / 180) * pow(sin((longitude * pi() / 180 - " . $longitude . " * pi() / 180) / 2),2))) * 1000)";

            $result = Db::name('gymnasium')
                ->where($where)
                ->where($distance . '< ' . 1000000000)
                ->field("$distance as distance,name,logo_image,id,is_join,is_activity")
                ->order('likes', 'desc')
                ->paginate(null, false, $this->paginate)
                ->each(function ($item) use ($join) {
                    $item['thumb_image'] = self::patch_cdn($item['logo_image']);
                    $item['distance'] = round(($item['distance'] / 1000), 2);
                    $item['is_join_text'] = $join[$item['is_join']];
                    return $item;
                });

            $this->success('获取成功', $result);
        } else {
            $this->error(ErrorCode::$ERROR['ERROR_METHOD']);
        }
    }

    /**
     * 场馆入驻协议
     * @ApiMethod (GET)
     */
    public function gymnasiumAgreement()
    {
        if ($this->request->isGet()) {

            $result = Db::name('content_gymnasium_agreement')->find();

            if ($result) {
                $result['content'] = self::patch_content($result['content']);

                $this->success('获取成功', $result['content']);
            } else {
                $this->error('获取失败');
            }
        } else {
            $this->error(ErrorCode::$ERROR['ERROR_METHOD']);
        }
    }

    /**
     * 教练入驻协议
     * @ApiMethod (GET)
     */
    public function coachAgreement()
    {
        if ($this->request->isGet()) {

            $result = Db::name('content_coach_agreement')->find();

            if ($result) {
                $result['content'] = self::patch_content($result['content']);

                $this->success('获取成功', $result['content']);
            } else {
                $this->error('获取失败');
            }
        } else {
            $this->error(ErrorCode::$ERROR['ERROR_METHOD']);
        }
    }

    /**
     * 购买协议
     * @ApiMethod (GET)
     */
    public function buyAgreement()
    {
        if ($this->request->isGet()) {

            $result = Db::name('content_purchase_agreement')->find();

            if ($result) {
                $result['content'] = self::patch_content($result['content']);

                $this->success('获取成功', $result['content']);
            } else {
                $this->error('获取失败');
            }
        } else {
            $this->error(ErrorCode::$ERROR['ERROR_METHOD']);
        }
    }

    /**
     * 励志名言 随机返回
     * @ApiMethod (GET)
     */
    public function inspirational()
    {
        if ($this->request->isGet()) {

            $rand = Db::name('content_inspirational')->max('id');
            $result = Db::name('content_inspirational')->where(['id' => rand(1, $rand)])->value('content');

            if ($result) {

                $this->success('获取成功', $result);
            } else {
                $this->error('获取失败');
            }
        } else {
            $this->error(ErrorCode::$ERROR['ERROR_METHOD']);
        }
    }

    /**
     * 获取小程序二维码
     * @ApiMethod (POST)
     */
    public function qrcode()
    {
        if ($this->request->isPost()) {

            $page = input('page');
            $scene = input('scene', '');
            $width = input('width', 480);
            $is_hyaline = input('is_hyaline', false);

            $pay = get_addon_config('epay');
            $app_id = $pay['wechat']['app_id'];
            $app_secret = $pay['wechat']['app_secret'];
            try {
                $result = (new WxSdk($app_id, $app_secret))->getWxQrcode($page, $scene, $width, $is_hyaline);
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }

            //判断是否是 json格式
            $result_json = json_decode($result, true);
            if ($result_json) {
                $this->error($result_json['errmsg']);
            } else {
                $this->success('获取成功', 'data:image/png;base64,' . base64_encode($result));
            }
        } else {
            $this->error(ErrorCode::$ERROR['ERROR_METHOD']);
        }
    }

    /**
     * 获取小程序二维码
     * @ApiMethod (GET)
     */
    public function content()
    {
        if ($this->request->isGet()) {

            $id = input('id');
            if (!$id) $this->error('请传入id');
            $result = Db::name('content_page')->where(['id' => $id])->find();
            if ($result) {
                $result['content'] = self::patch_content($result['content']);
                $this->success('获取成功', $result);
            } else {
                $this->error('获取失败，未找到数据');
            }
        } else {
            $this->error(ErrorCode::$ERROR['ERROR_METHOD']);
        }
    }

    /**
     * 测试
     */
    public function test()
    {
        // 场馆审核通过，下发通知
        $pay = get_addon_config('epay');
        $app_id = $pay['wechat']['app_id'];
        $app_secret = $pay['wechat']['app_secret'];
        $data = [
            'thing18' => ['value' => '肌肉人俱乐部'],
            'thing4'  => ['value' => '请第一时间修改密码，防止造成您的损失'],
            'phrase5' => ['value' => '审核通过'],
            'thing11' => ['value' => '点击查看详情'],
        ];
        $find_open = Db::name('user')
            ->alias('user')
            ->where(['gymnasium.id' => 379])
            ->join('gymnasium gymnasium', 'user.id = gymnasium.user_id', 'LEFT')
            ->field('user.open_id')
            ->find();
        $result = (new WxSdk($app_id, $app_secret))->subscribeSend('o7p1X4-l_5i3ZCuMRKJxxznHUyIc', 'pZBlRlk_qVjPUbbS1_04XHTd_98uGbSfV5P3mLy2BWY', 'pages/content/index?id=4', $data);
        var_dump($result);
    }
}
